package Thread.New.带返回值的线程创建;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 功能概要：
 *
 * @author linbingwen
 * @since  2016年6月8日
 */
@SuppressWarnings("all")
public class FutureTest {

    public static void main(String[] args) {
        System.out.println("main Thread begin at:"+ System.nanoTime());
        //打印当前时间的毫秒值
        ExecutorService executor = Executors.newCachedThreadPool();
        //获取线程池

        Future<Integer> result1 = executor.submit(new HandleCallable("1"));
        Future<Integer> result2 = executor.submit(new HandleCallable("2"));
        Future<Integer> result3 = executor.submit(new HandleCallable("3"));
        ///分别执行线程并获取对应线程的返回值
        executor.shutdown();
        //执行完毕所有线程,将线程池关闭
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        /*打印各个线程的执行结果,使用Future的get方法获取*/
        try {
            System.out.println("task1运行结果:"+result1.get());
            System.out.println("task2运行结果:"+result2.get());
            System.out.println("task3运行结果:"+result3.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("main Thread finish at:"+ System.nanoTime());
    }

}

@SuppressWarnings("all")
class HandleCallable implements Callable<Integer>{
    private String name;
    //创建继承Callable的类
    public HandleCallable(String name) {
        this.name = name;
    }

    //覆写call方法,实现线程任务
    @Override
    public Integer call() throws Exception {
        System.out.println("task"+ name + "开始进行计算");
        Thread.sleep(3000);
        int sum = new Random().nextInt(300);
        int result = 0;
        for (int i = 0; i < sum; i++) {
            result += i;
        }
        return result;
    }
}
